package com.gitee.chili.leisure;

import com.gitee.chili.leisure.util.Utils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;

/**
 * HeaderInterceptor
 *
 * @author week solider
 * @version v1.0
 * @since 2019/12/26
 */

@SuppressWarnings("all")
@Slf4j
public class HeaderInterceptor {

    public Map<String, Collection<String>> apply(HeaderProperties properties) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();

            String contentType = request.getHeader("Content-Type");
            log.info("feign request header Content-Type : [ {} ]", contentType);

            String value = Utils.defaultValue(contentType, "appalication/json;charset=utf-8");

//            String body = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
//            String timestamp = DateUtil.valueOfTimestamp();
//            String token = properties.getToken();
//            String sign = MD5Utils.encryption(CommUtils.connect(body, timestamp, token));
//
            Map<String, Collection<String>> headers = Maps.newHashMap();
//            headers.put("timestamp", Collections.singletonList(timestamp));
//            headers.put("token", Collections.singletonList(token));
//            headers.put("sign", Collections.singletonList(sign));

            headers.put("Content-Type", Collections.singletonList(value));

            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String values = request.getHeader(name);
                    headers.put(name, Lists.newArrayList(values));
                }
                log.info("feign interceptor header:{}", headers);
            }
            return headers;
        } catch (Exception e) {
            log.error("请求头信息添加异常:{}", e.getMessage(), e);
        }
        return null;
    }
}
